package com.ujcms.cms.core.web.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @author 10100
 * @license (C) Copyright 2020-2050,  Corporation Limited.
 * @contact wang.he@cpe-smartcity.com
 * @date 2021/5/6 20:44
 * @description 对options 请求处理
 */
public class CorsFilter implements Filter {

    private static final String OPTIONS = "OPTIONS";

    private boolean useGateway;

    @Override
    public void init(FilterConfig filterConfig) {
        // TODO Auto-generated method stub
    }

    public CorsFilter(boolean useGateway) {
        this.useGateway = useGateway;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        if (!useGateway) {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods",
                    "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "");
            response.setHeader("Access-Control-Allow-Headers",
                    "Content-Type, x-requested-with, X-Custom-Header, Authorization,language");

            /*如果是option请求, 手动添加header*/
            if (OPTIONS.equals(request.getMethod())) {
                /*如果是option请求， 直接放行， 否则浏览器报 It does not have HTTP ok status. 错误*/
                response.setStatus(HttpServletResponse.SC_OK);
                return;
            }
        }
        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }
}